package com.wqnmdb.im.client;

import com.alibaba.fastjson.JSONObject;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@Slf4j
public class NettyClient {

    private ChannelFuture future;

    /**
     * 启动客户端
     */
    public void start() {
        // 首先，netty通过Bootstrap启动客户端
        Bootstrap client = new Bootstrap();
        // 第1步 定义线程组，处理读写和链接事件，没有了accept事件
        EventLoopGroup group = new NioEventLoopGroup();
        client.group(group);
        // 第2步 绑定客户端通道
        client.channel(NioSocketChannel.class);

        client.option(ChannelOption.TCP_NODELAY, true);
        // 第3步 给NIoSocketChannel初始化handler， 处理读写事件
        client.handler(new NettyClientInitializer());

        // 连接服务端

        try {
            future = client.connect("127.0.0.1", 8999).sync();
            log.info("客户端成功....");
            // 等待连接被关闭
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            group.shutdownGracefully();
        }
    }

    public void closeClient(){
        future.channel().close();
    }

    public static void main(String[] args) throws InterruptedException {
        //启动netty客户端
        int i = 0;
        boolean bool = true;
        while (true){
            try {
                i++;
                NettyClient nettyClient = new NettyClient();
                nettyClient.start();
            }catch (Exception e){
                log.info("连接异常");
                bool = false;
                TimeUnit.SECONDS.sleep(3);
            }finally {
                if (bool){
                    log.info("连接成功");
                    break;
                }
                if (i > 10){
                    log.info("连接超时，进入下个纪元");
                    i = 0;
                    break;
                }
            }
        }
    }
}